//
//  HomeTableViewController.swift
//  weibo---练习
//
//  Created by 胡海波 on 15/6/24.
//  Copyright © 2015年 胡海波. All rights reserved.
//

import UIKit
import SVProgressHUD

class HomeViewController: BaseViewController,StatusCellDelegate {


    var statusList: [Status]? {
        didSet{

            tableView.reloadData()

            refreshControl?.endRefreshing()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()


        vistorView?.setupViewInfo("visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜", isHome: true)

        // 用户登陆后才能加载网络数据，如果没有用户登陆，直接返回
        if userLogin == false {

            return
        }

        setupNavgationButton()
        prepareTableView()
        prepareRefreshing()


    }

    ///  缓存行高
    lazy var rowHightCache = [Int:CGFloat]()

    override func viewDidAppear(animated: Bool) {

        vistorView?.startAnimation()
    }

    // 加载微博数据
    func loadData(){

        // 开始刷新不会触发监听方法，会显示刷新控件
        refreshControl?.beginRefreshing()

        // 下拉刷新代号
        var since_id = statusList?.first?.id ?? 0

        // 上拉刷新，取数组中最后一条的 id
        var max_id = 0

        if pullRefreshingFlag {
            since_id = 0
            max_id = statusList?.last?.id ?? 0
        }


        Status.loadStatus(since_id,max_id: max_id) {(statuses, error) -> () in

            if error != nil {
                // 不要把错误的相信信息告诉用户，程序员应该多测试！
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }

            // 提示，后续会有下拉刷新，没有新微博的情况，不要抱错！
            if statuses == nil {
                print("没有数据")
                return
            }
            // 判断是否下拉刷新，将新的数据添加到愿有数据后面
            if since_id > 0 {

                self.statusList = statuses! + self.statusList!

            } else if max_id > 0{
                // 执行该句会调用 上拉刷新
                self.statusList = self.statusList! + statuses!
                self.pullRefreshingFlag = false
            } else {

                // 初始刷新
                self.statusList = statuses
            }
        }
    }




    override func didReceiveMemoryWarning() {
        ///  清理行高缓存
        rowHightCache.removeAll()
    }

    // MARK -- StatusCell代理  方法的实现
    func StatusCellDidSelectedPhotoes(cell: StatusCell, photoIndex: Int) {

        if cell.status?.calLargeImageURLs == nil {

            return
        }

        let vc = PhotoBrowserViewController(urls: cell.status!.calLargeImageURLs!, index: photoIndex)
        
        // 设置专场代理
        vc.transitioningDelegate = self
        // 设置专场样式
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom

        presentViewController(vc, animated: true, completion: nil)
    }
//*****************************************************************************//
//*****************************************************************************//
    // MARK: -- 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return statusList?.count ?? 0
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let status =  statusList![indexPath.row]

        let ID = StatusCell.cellReusedIdentifier(status)

        let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath) as! StatusCell
        cell.photoDelegate = self

        cell.status = status

        // 判断是否是最后一行
        if indexPath.row == statusList!.count - 1 {
            pullRefreshingFlag = true
            loadData()
        }

        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 1.取出当前行的模型数据
        let status = statusList![indexPath.row]

        // 判断是否缓存了行高，缓存了就返回行高
        if rowHightCache[status.id] != nil {

            return rowHightCache[status.id]!
        }
        
        // 2.获取cell
        // 取出可重用ID
        let ID = StatusCell.cellReusedIdentifier(status)

        // 定义一个类 默认为原创微博
        var cls: AnyClass = StatusNormalCell.self

        if ID == HBStatusForwardCellReusedIdentified {

            cls = StatusForwardCell.self
        }

        let cell = cls.new() as! StatusCell


        // 3.返回行高
        let height = cell.rowHight(status)
        rowHightCache[status.id] = height
        return height
    }
//*****************************************************************************//
//*****************************************************************************//
    // 设置转场动画代理
    let popoverAnimate = PopoverAnimation()

    func titleButtonClicked() {
        let sb = UIStoryboard(name: "FriendGroup", bundle: nil)
        let vc = sb.instantiateViewControllerWithIdentifier("FriendGroupSB")

        vc.transitioningDelegate = popoverAnimate

        vc.modalPresentationStyle = UIModalPresentationStyle.Custom

        popoverAnimate.presentedFrame = CGRectMake(112, 56, 180, 300)

        presentViewController(vc, animated: true, completion: nil)
    }

//*****************************************************************************//
//*****************************************************************************//
    // 设置导航栏按钮
    func setupNavgationButton() {

        if sharedUserAccount == nil {
            return
        }

        // 1.设置导航栏左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", highlightImageName: nil)

        // 2.设置导航栏右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", highlightImageName: nil)

        // 设置导航栏标题

        let titleButton = TitleButton.button(sharedUserAccount!.name!)

        titleButton.addTarget(self, action: "titleButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)

        navigationItem.titleView = titleButton

    }

//*****************************************************************************//
//*****************************************************************************//

    // 准备tableView
    private func prepareTableView() {

        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: HBStatusForwardCellReusedIdentified)
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: HBStatusNormalCellReusedIdentified)

        // 取消cell的分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    }


    // 准备刷新工作
    private func prepareRefreshing(){

        refreshControl = HBRefreshControl()

        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)

        loadData()
        
    }


    ///   上拉刷新标记
    private var pullRefreshingFlag = false
    
    // 设置展现标记
    private var isPresented = false
}

extension HomeViewController:UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning {
    
    // 提供返回专场动画modal的对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = true
        
        return self
    }
    
    // 返回提供专场 Dismiss 动画的对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = false
        return self
    }
    
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        
        return 0.5
    }
    
    // 一旦实现，需要程序员设置动画
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        let viewKey = (isPresented == true ? UITransitionContextToViewKey : UITransitionContextFromViewKey)
        
        let targetView = transitionContext.viewForKey(viewKey)
        
        if targetView == nil {
            return
        }
        
        
        if isPresented {
        
            // 添加toView
            transitionContext.containerView()?.addSubview(targetView!)
            targetView!.alpha = 0
            
            // 设置动画
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                
                targetView!.alpha = 1
                }, completion: { (_) -> Void in
                    
                    transitionContext.completeTransition(true)
            })
        } else {
            
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                targetView!.alpha = 0
                }, completion: { (_) -> Void in
                    
                    targetView?.removeFromSuperview()
                    transitionContext.completeTransition(true)
            })
        }
        
        
    }
    
}
